package com.example.my_bookkeeping.ui.record;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.my_bookkeeping.R;
import com.example.my_bookkeeping.data.manager.BookKeepManager;
import com.example.my_bookkeeping.data.manager.CategoryManager;
import com.google.android.material.tabs.TabLayout;

import java.time.LocalDateTime;
import java.util.ArrayList;

public class RecordActivity extends AppCompatActivity {

    private EditText editTextAmount;
    private Spinner spinnerCategory;
    private EditText editTextNote;
    private EditText editTextDate;
    private TabLayout typeTabLayout;

    private CategoryManager categoryManagerInstance;
    private CategorySpinnerAdapter categoryAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_record);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        editTextAmount = findViewById(R.id.editText_amount);
        spinnerCategory = findViewById(R.id.spinner_category);
        editTextNote = findViewById(R.id.editText_note);
        editTextDate = findViewById(R.id.editTextDate_datetime);
        typeTabLayout = findViewById(R.id.tabLayout_type);

        Button saveButton = findViewById(R.id.button_save);
        saveButton.setOnClickListener(v -> {
            // 保存数据
            // 确定是支出还是收入
            boolean isIncome = typeTabLayout.getSelectedTabPosition() == 1;

            // 获取金额
            String amountStr = editTextAmount.getText().toString();
            double amount;
            if (amountStr.isEmpty()) {
                editTextAmount.setError(getString(R.string.record_warning_invalid_amount));
                return;
            }
            amount = Math.round(Double.parseDouble(amountStr)*100) / 100.0;

            // 获取其他数据
            String category = spinnerCategory.getSelectedItem().toString();
            String note = editTextNote.getText().toString();
            String date = editTextDate.getText().toString();
            if (date.isEmpty()) {
                // 如果date为空，则使用当前时间
                date = LocalDateTime.now().toString().substring(0, 10);
            }
            else if (date.length() != 10) {
                // 判断date是否符合格式
                // 显示错误信息
                editTextDate.setError(getString(R.string.record_warning_invalid_date));
                return;
            }

            // 保存数据
            BookKeepManager.getInstance().add(date, amount, category, note, isIncome);
            finish();
        });

        Button cancelButton = findViewById(R.id.button_cancel);
        cancelButton.setOnClickListener(v -> {
            // 取消保存
            finish();
        });

        ImageButton backButton = findViewById(R.id.imageButton_close);
        backButton.setOnClickListener(v -> {
            // 返回上一页
            finish();
        });

        // 初始化category spinner
        categoryManagerInstance = CategoryManager.getInstance();
        categoryAdapter = new CategorySpinnerAdapter(categoryManagerInstance.getExpenseCategoryList());
        spinnerCategory.setAdapter(categoryAdapter);

        // 设置TabLayout，切换收入和支出分类
        typeTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    categoryAdapter.setCategories(categoryManagerInstance.getExpenseCategoryList());
                } else {
                    categoryAdapter.setCategories(categoryManagerInstance.getIncomeCategoryList());
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private class CategorySpinnerAdapter extends ArrayAdapter<String> {
        public CategorySpinnerAdapter(ArrayList<String> _categories) {
            super(RecordActivity.this, android.R.layout.simple_spinner_item, _categories);
        }
        public void setCategories(ArrayList<String> categories) {
            clear();
            addAll(categories);
            notifyDataSetChanged();
        }
    }
}